$.fn.reportgrid = function (options,data) {
    if( options == 'reload' ){
        var opt = $(this).data();
        $.extend(opt.queryParams,data);
        loadUrl($(this),opt);
        return;
    }
    var opt = {
        page:1,limit:10,pagination:true,limits:[10,20,30,50,100],queryParams:{}
    };
    $.extend(opt,options);
    var table = $(this);
    if(opt.width)table.width(opt.width);
    table.data(opt);

    //replace head td
    table.find('.report-head td').each(function () {
        $(this).html("<div class='cell'>"+$(this).html()+"</div>");
    });

    var columns = opt.columns;
    if( !opt.fixed ){
        var tableWidth = table.width(),columnsWidth=0;
        for( var i=0 ; i<columns.length ; i++ ){
            columnsWidth += columns[i].width;
        }

        var rate = app.div(columnsWidth,tableWidth);
        for( var i=0 ; i<columns.length ; i++ ){
            columns[i].width = app.div(columns[i].width,rate);
        }
    }

    markTdsIndex(table);
    //set cell width
    for( var i=0 ; i<columns.length ; i++ ){
        table.find('.report-head td[i="'+i+'"] .cell').width(columns[i].width);
    }

    loadUrl(table,opt);

    function loadUrl(table,options) {
        options.queryParams.page = options.page;
        options.queryParams.limit = options.limit;

        var data =$.extend(options.queryParams,{loginUserId:top.loginUserId,customerId:top.customerId,loginCompanyId:top.loginCompanyId,loginCompanyLogicalCode:top.loginCompanyLogicalCode});

        $.ajax({
            url:options.url,
            data:data,
            type:'POST',
            dataType:'json',
            success:function(resp){
                if( resp.result == 2 ){
                    top.layer.confirm('无权限或者登陆过期，即将跳转到登陆界面', {icon: 3, title:'提示'}, function(index){
                        top.app.toLogin();
                        top.layer.close(index);
                    });
                }else{
                    loadData(table,options,resp,1);
                }
            }
        });
    }

    function loadData(table,opt,resp,currPageNum) {
        table.find('.report-body').remove();
        var rows = resp.rows,columns = opt.columns;
        for( var i=0 ; i<rows.length ; i++ ){

            var tr = $('<tr class="report-body"></tr>');
            var row = rows[i];
            for( var k=0 ; k<columns.length ; k++ ){
                var td = $('<td></td>');
                var cell = $('<div class="cell"></div>');
                cell.width(columns[k].width);
                cell.append(getValue(row,columns[k]));
                setCellStyle(cell,columns[k]);
                td.append(cell);
                tr.append(td);
            }
            table.append(tr);
        }

        if(opt.pagination){
            createPage(opt,resp.total,table,currPageNum);
        }
    }

    function setCellStyle(cell,column) {
        if( column.n == 'number' || column.n=='money'){
            cell.css({"text-align":"right","padding-right":"10px"});
        }
        if( column.align ){
            var o = {};
            o["text-align"] = column.align;
            o["padding-"+column.align] = "10px";
            cell.css(o);
        }
    }

    function getValue(row,column) {
        var value;
        if( column.formatter ){
            value = column.formatter(row,row[column.field],column);
        }else{
            value = row[column.field];
        }
        if(value){
            if( column.n == 'number' )value = (app.div(value,app.DIV)+'').replace('.00','');
            if( column.n == 'money' )value = (app.div(value,app.DIV)+'');
            if( column.n == 'date' )value = app.time2str(value);
        }

        if( value == undefined || value==null){
            return '';
        }
        return value;
    }

    function markTdsIndex(table) {
        var index = 0,nextIndex = 0;
        table.find('tr:first td').each(function () {
            var colspan = $(this).attr('colspan');
            if( colspan ){
                colspan = parseInt(colspan);
                for( var k=0 ; k<colspan ; k++ ){
                    table.find('tr:eq(1) td').eq(nextIndex+k).attr('i',index++);
                }
                nextIndex += colspan;
            }else{
                $(this).attr('i',index++);
            }
        });
    }

    function createPage(options,total,table,currPageNum) {
        table.parent().parent().find('div[page="on"]').remove();
        var totalPage = total % options.limit ==0 ? total/options.limit : Math.floor(total/options.limit)+1 ;

        var page = $('<div class="vui-page"></div>');
        page.append('<span class="vui-page-count">共 '+total+' 条</span>');
        page.append(getPagePre(options,total,table,currPageNum));
        page.append(getPageNext(options,total,table,currPageNum,totalPage));
        if(!options.simplePagination){
            page.append(getPageLimits(options,total,table,currPageNum));
        }
        page.append(getPageSkip(options,total,table,currPageNum));

        var pageDiv = $("<div page='on' style='background: #ffffff;'></div>");
        pageDiv.append(page);
        table.parent().parent().append(pageDiv);
    }

    function getPageSkip(options,total,table,currPageNum) {
        var skip = $('<span class="vui-page-skip">到第<input type="text" value="'+currPageNum+'"/>页</span>');
        var button = $('<button type="button">确定</button>');
        skip.append(button);
        button.click(function () {
            options.page = $(this).parent().find('input').val();
            loadUrl(table,options);
        });
        skip.find('input').click(function () {
            $(this).select();
        });
        return skip;
    }


    function getPageLimits(options,total,table,currPageNum) {
        var limit = $('<span class="vui-page-limit"></span>');
        var select = $('<select></select>');
        for( var i=0 ; i<options.limits.length ; i++ ){
            var limitsNum = options.limits[i];
            var option = $('<option value="'+limitsNum+'">'+limitsNum+' 条/页</option>');
            if( options.limit == limitsNum ){
                option.attr("selected","selected");
            }
            select.append(option);
        }
        select.change(function () {
            var limitValue = $(this).find('option:selected').val();
            options.page = currPageNum;
            options.limit = limitValue;
            loadUrl(table,options);
        });
        limit.append(select);
        return limit;
    }

    function getPagePre(options,total,table,currPageNum) {
        var pre = $('<a href="javascript:;" class="vui-page-prev" data-page="'+(currPageNum-1)+'">上一页</a>');
        if( currPageNum == 1 ){
            pre.addClass("vui-page-disabled");
        }else{
            pre.click(function () {
                options.page = $(this).data('page');
                loadUrl(table,options);
            });
        }
        return pre;
    }

    function getPageNext(options,total,table,currPageNum,totalPage) {
        var next = $('<a href="javascript:;" class="vui-page-next" data-page="'+(currPageNum+1)+'">下一页</a>');
        if( currPageNum == totalPage ){
            next.addClass("vui-page-disabled");
        }else{
            next.click(function () {
                options.page = $(this).data('page');
                loadUrl(table,options);
            });
        }
        return next;
    }
};

